package vikaa.ui;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang3.StringEscapeUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.weibo.sdk.android.Oauth2AccessToken;
import com.weibo.sdk.android.Weibo;
import com.weibo.sdk.android.WeiboAuthListener;
import com.weibo.sdk.android.WeiboDialogError;
import com.weibo.sdk.android.WeiboException;
import com.weibo.sdk.android.sso.SsoHandler;
import com.weibo.sdk.android.util.Utility;
import com.weibo.sdk.android.keep.AccessTokenKeeper;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import vikaa.adapter.AdapterRecommandWowo;
import vikaa.bean.Space;
import vikaa.bean.SpaceOauth;
import vikaa.tools.HttpUtil;
import vikaa.tools.Logger;
import vikaa.tools.StringUtils;
import vikaa.wowo.R;
import vikaa.wowo.cache.AuthoSharePreference;
import vikaa.wowo.cache.DefaultValueSharePreference;
import vikaa.wowo.cache.UserInfoSharePreference;

public class LookAround extends Activity implements OnItemClickListener{
	private Weibo mWeibo;
	public static Oauth2AccessToken accessToken ;
	private static final int ACCESS_SUSSESS = 1;
	private static final int ACCESS_FAIL = 0;
	private ListView wowolistview;
	private AdapterRecommandWowo mAdapter;
	private ArrayList<Space> mList = new ArrayList<Space>();
	private String uid;
	private RelativeLayout lookaroundBtn;
	private LinearLayout header;
	private RelativeLayout loadingRl;
	private boolean loginFlag ;
	
	SsoHandler mSsoHandler;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.lookaround);
		mWeibo = Weibo.getInstance(WeiboConstParam.CONSUMER_KEY, WeiboConstParam.REDIRECT_URL);
		uid = UserInfoSharePreference.getUid(LookAround.this);
		lookaroundBtn = (RelativeLayout)findViewById(R.id.lookaoundBtn);
		header = (LinearLayout)findViewById(R.id.header);
		loginFlag = DefaultValueSharePreference.getLoginFlag(LookAround.this);
		loadingRl = (RelativeLayout)findViewById(R.id.loadingRl);
		loadingRl.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				
			}
		});
		loadingRl.setVisibility(View.INVISIBLE);
		if(loginFlag){
			Logger.i(""+ loginFlag);
			loadingRl.setVisibility(View.VISIBLE);
			initview();
			String token = AuthoSharePreference.getToken(LookAround.this);
			String oauth_id = AuthoSharePreference.getUid(LookAround.this);
	        new OauthUserThread("sina2", oauth_id, token).start();
		}else{
			Logger.i(""+ loginFlag);
			initview();
			new downMywowoThread().start();
		}
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if(resultCode != RESULT_OK) return;
		if(requestCode == 10){
			login();
		}
		/**
         * 下面两个注释掉的代码，仅当sdk支持sso时有效，
         */
        if(mSsoHandler!=null){
            mSsoHandler.authorizeCallBack(requestCode, resultCode, data);
        }
	}	
	public void initview(){
		try {
            Class sso=Class.forName("com.weibo.sdk.android.sso.SsoHandler");
            lookaroundBtn.setVisibility(View.VISIBLE);
        } catch (ClassNotFoundException e) {
        	e.printStackTrace();
        }
		lookaroundBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				mSsoHandler =new SsoHandler(LookAround.this,mWeibo);
	            mSsoHandler.authorize( new AuthDialogListener());
				//login();
			}
		});
		wowolistview = (ListView) findViewById(R.id.wowolist);
		wowolistview.setOnItemClickListener(this);
		
		mAdapter = new AdapterRecommandWowo(LookAround.this, mList, wowolistview);
        wowolistview.setAdapter(mAdapter);
	}
	private void login(){
		/*//showPopupWindow();
		//AccessTokenKeeper.clear(LookAround.this);
		//loadingRl.setVisibility(View.VISIBLE);
		String token = AuthoSharePreference.getToken(LookAround.this);
		String oauth_id = AuthoSharePreference.getUid(LookAround.this);
		//if (StringUtils.isEmpty(token)){
		Logger.i("a");
		//loadingRl.setVisibility(View.GONE);
		Logger.i(token +"  " + oauth_id);
		authroized();
		//lookaroundBtn.setClickable(false);
		//}
		else{
			Logger.i(token +"  " + oauth_id);
			Utility.setAuthorization(new Oauth2AccessTokenHeader());
	        AccessToken accessToken = new AccessToken(token, WeiboConstParam.CONSUMER_SECRET);     
	        Weibo.getInstance().setAccessToken(accessToken);
	        new OauthUserThread("sina2", oauth_id, token).start();
		}*/
		mSsoHandler =new SsoHandler(LookAround.this,mWeibo);
        mSsoHandler.authorize( new AuthDialogListener());
	}
	Handler mhandler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			switch(msg.what){
			case 1:
				header.setVisibility(View.GONE);
				mAdapter.notifyDataSetChanged();
				break;
			case 2:
				mList.clear();
				if(msg.obj != null){
					ArrayList<Space> strings = (ArrayList<Space>) msg.obj;
					if(!strings.isEmpty()){
						mList.addAll(strings);
						mAdapter.notifyDataSetChanged();
					}
				}
				break;
			case 3://info = null
				header.setVisibility(View.GONE);
				TextView tv1 = (TextView)findViewById(R.id.emptyTv);
				TextView tv2 = (TextView)findViewById(R.id.emptydivider);
				tv1.setVisibility(View.VISIBLE);
				tv2.setVisibility(View.VISIBLE);
				break;
			case 4://access error
				header.setVisibility(View.GONE);
				if(msg.obj != null){
					Toast.makeText(LookAround.this, (String)msg.obj, Toast.LENGTH_SHORT).show();
				}
				else
					Toast.makeText(LookAround.this, R.string.server_crash, Toast.LENGTH_SHORT).show();
				break;
			case 5://network error
				header.setVisibility(View.GONE);
				Toast.makeText(LookAround.this, getString(R.string.network_crash), Toast.LENGTH_SHORT).show();
				break;
			case 0://refresh fail
				Toast.makeText(LookAround.this, getString(R.string.info_msg2), Toast.LENGTH_SHORT).show();
				break;
			}
		}
		
	};
	class downMywowoThread extends Thread{
		private boolean isrun = true;
		
		@Override
		public void run() {
			while(isrun){
			isrun =false;
			Map<String, String> map = new HashMap<String, String>();
			map.put("max_count", "10");
			String url = HttpUtil.BASE_URL + "space/launch";
			try {
				
				mList.clear();
				JSONObject jsonObj = new JSONObject(HttpUtil.postRequest(url, map));
				String result = jsonObj.getString("result");
				if(result.equals("1")){
					JSONArray mySpacelist = jsonObj.getJSONArray("info");
					for(int i=0;i<mySpacelist.length();i++){
						Space list = new Space();
						list.setCount(mySpacelist.getJSONObject(i).getString("twitterCount"));
						list.setNumber(mySpacelist.getJSONObject(i).getString("memberCount"));
						list.setManagerCount(mySpacelist.getJSONObject(i).getString("managerCount"));
						list.setTotalMemberCount(String.valueOf(Integer.valueOf(list.getNumber())+Integer.valueOf(list.getManagerCount())));
						list.setSpace_id(mySpacelist.getJSONObject(i).getString("space_id"));
						list.setSpacename(StringEscapeUtils.unescapeHtml4(mySpacelist.getJSONObject(i).getString("spacename")));
						String cover = mySpacelist.getJSONObject(i).getString("cover");
						list.setCover(cover);
						list.setState(mySpacelist.getJSONObject(i).getString("state"));
						ArrayList<SpaceOauth> solist = new ArrayList<SpaceOauth>();
						for(int j =0;j<mySpacelist.getJSONObject(i).getJSONArray("spaceoauth").length();j++){
							SpaceOauth so = new SpaceOauth();
							so.setUid(mySpacelist.getJSONObject(i).getJSONArray("spaceoauth").getJSONObject(j).getString("uid"));
							so.setCredits(mySpacelist.getJSONObject(i).getJSONArray("spaceoauth").getJSONObject(j).getString("credits"));
							so.setRole(mySpacelist.getJSONObject(i).getJSONArray("spaceoauth").getJSONObject(j).getString("role"));
							so.setCallname(mySpacelist.getJSONObject(i).getJSONArray("spaceoauth").getJSONObject(j).getString("callname"));
							solist.add(so);
						}
						list.setSpaceoauth(solist);
						mList.add(list);
					}
					Message msg = mhandler.obtainMessage(1);
					msg.sendToTarget();
				}
				else if(result.equals("0")){
					Message msg = mhandler.obtainMessage(4);
					msg.obj = jsonObj.getString("msg");
					msg.sendToTarget();
				}
				else{
					Message msg = mhandler.obtainMessage(5);
					msg.obj = jsonObj.getJSONObject("info").getString("error");
					msg.sendToTarget();
				}
			} catch (JSONException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
			}
		}
	}
	public void onItemClick(AdapterView<?> arg0, View view, int position, long arg3) {
		if(mList.get(position).getState().equals("1")){
			Toast.makeText(LookAround.this, getString(R.string.msg_noaccess_look), Toast.LENGTH_SHORT).show();
		}else{
			String id = mList.get(position).getSpace_id();
	    	String spacename = mList.get(position).getSpacename();
	    	String count = mList.get(position).getCount();
	        Intent intent = new Intent(LookAround.this,TimelineForLookAround.class);
	        intent.putExtra("sid", id);
	        intent.putExtra("uid", uid);
	        intent.putExtra("role", "0");
	        intent.putExtra("spacename", spacename);
	        intent.putExtra("count", count);
	        intent.putExtra("cover", mList.get(position).getCover());
	        intent.putExtra("member", mList.get(position).getNumber());
	        intent.putExtra("host", mList.get(position).getManagerCount());
	        intent.putExtra("state", mList.get(position).getState());
	        startActivityForResult(intent, 10);
		}
	}
	public void authroized(){
		
		mWeibo.authorize(LookAround.this, new AuthDialogListener());
	}
	Handler handler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			switch(msg.what){
			case ACCESS_SUSSESS:
				Bundle b = msg.getData();
				String phone_validate = b.getString("phone_validate");
				String uid = b.getString("uid");
				String sessid  = b.getString("phpsessid");	
				if(phone_validate.equals("1")){
					Intent mywowoIntent = new Intent(LookAround.this,Mywowo.class);
					mywowoIntent.putExtra("uid", uid);
					//save ssid
					AuthoSharePreference.putCookie(LookAround.this, sessid );
					startActivity(mywowoIntent);
					finish();
				}
				else{
					Intent loginIntent = new Intent(LookAround.this,WowoActive.class);
					loginIntent.putExtra("uid", uid);
					startActivity(loginIntent);
					finish();
				}
				//loadingRl.setVisibility(View.INVISIBLE);
				break;
			case ACCESS_FAIL:
				loadingRl.setVisibility(View.INVISIBLE);
				lookaroundBtn.setClickable(true);
				if(((String)msg.obj).equals("expired_token") || ((String)msg.obj).equals(getString(R.string.OAUTH_AccessToken_ERROR)) || ((String)msg.obj).equals("invalid_access_token") || ((String)msg.obj).equals("source paramter(appkey) is missing")){
					Logger.i("au");
					authroized();
				}
				else{
					Toast.makeText(LookAround.this, /*getString(R.string.network_not_connected)*/(String)msg.obj , Toast.LENGTH_SHORT).show();
				}
				break;
			}
		}
	};
	class OauthUserThread extends Thread {
		private boolean isrun = true;
		private  String oauth_type;
		private String oauth_id;
		private String oauth_token;
		public OauthUserThread(String oauth_type, String oauth_id,
				String oauth_token) {
			this.oauth_type = oauth_type;
			this.oauth_id = oauth_id;
			this.oauth_token = oauth_token;
		}
		@Override
		public void run() {
			while(isrun){
			Map<String, String> map = new HashMap<String, String>();
			map.put("oauth_type", oauth_type);
			map.put("oauth_token", oauth_token);
			map.put("oauth_id", oauth_id);
			TelephonyManager tm = (TelephonyManager) getBaseContext().getSystemService(Context.TELEPHONY_SERVICE);
			String tmDevice ;
		    tmDevice = "" + tm.getDeviceId();
		    if(StringUtils.isEmpty(tmDevice)){
		    	tmDevice = oauth_id;
		    }
			try {
				map.put("device_token", tmDevice);
				map.put("client_browser", LookAround.this.getPackageManager().getPackageInfo("com.vikaa.wowo", 0).versionCode + "");
				map.put("client_screen", getWindowManager().getDefaultDisplay().getWidth() + "x" + getWindowManager().getDefaultDisplay().getHeight());
				map.put("client_os", "android " + android.os.Build.VERSION.RELEASE);
				map.put("client_type", android.os.Build.MODEL);
			} catch (NameNotFoundException e1) {
				e1.printStackTrace();
			}
			String url = HttpUtil.BASE_URL + "user/oauthlogin";
			try {
				JSONObject jsonObj = new JSONObject(HttpUtil.postRequest(url, map));
				String result = jsonObj.getString("result");
				if(result.equals("1")){
					isrun = false;
					String phone_validate = jsonObj.getJSONObject("info").getString("phone_validate");
					String uid = jsonObj.getJSONObject("info").getString("uid");
					String phpSESSID = null;
					if(phone_validate.equals("1")){
					phpSESSID = jsonObj.getJSONObject("info").getString("PHPSESSID");}
					UserInfoSharePreference.putNickname(LookAround.this, jsonObj.getJSONObject("info").getString("nickname"));
					UserInfoSharePreference.putUid(LookAround.this, uid);
					UserInfoSharePreference.putAvater(LookAround.this, jsonObj.getJSONObject("info").getString("avatar"));
					UserInfoSharePreference.putEmail(LookAround.this, jsonObj.getJSONObject("info").getString("email"));
					UserInfoSharePreference.putPhone(LookAround.this, jsonObj.getJSONObject("info").getString("phone"));
					UserInfoSharePreference.putCrash(LookAround.this, "0");
					Message msg = handler.obtainMessage(ACCESS_SUSSESS);
					Bundle b = msg.getData();
					b.putString("phone_validate", phone_validate);
					b.putString("phpsessid", phpSESSID);
					b.putString("uid", uid);
					handler.sendMessage(msg);
				}else if(result.equals("0")){
					isrun = false;
					String error = jsonObj.getString("msg");
					Message msg = handler.obtainMessage(ACCESS_FAIL);
					msg.obj = error;
					handler.sendMessage(msg);
				}
				else{
					isrun = false;
					String error = jsonObj.getJSONObject("info").getString("error");
					Message msg = handler.obtainMessage(ACCESS_FAIL);
					msg.obj = error;
					handler.sendMessage(msg);
				}
			}  catch (Exception e) {
				isrun = false;
				e.printStackTrace();
				}
			}
		}
		
	}
	
	class AuthDialogListener implements WeiboAuthListener {
		@Override
		public void onComplete(Bundle values) {
			String token = values.getString("access_token");
			String expires_in = values.getString("expires_in");
			Logger.i(expires_in);
			LookAround.accessToken = new Oauth2AccessToken(token, expires_in);
			if (LookAround.accessToken.isSessionValid()) {
				String oauth_id  = values.getString("uid");
			    AuthoSharePreference.putUid(LookAround.this, oauth_id );
			    AuthoSharePreference.putToken(LookAround.this, token );
			    AuthoSharePreference.putExpires(LookAround.this, expires_in);
			    String oauth_type = "sina2";
			    loadingRl.setVisibility(View.VISIBLE);
			    AccessTokenKeeper.keepAccessToken(LookAround.this, accessToken);
				new OauthUserThread(oauth_type, oauth_id, token).start();
			}
		}

		@Override
		public void onWeiboException(WeiboException e) {
			Toast.makeText(getApplicationContext(),	"Auth exception : " + e.getMessage(), Toast.LENGTH_LONG)
			.show();
			loadingRl.setVisibility(View.INVISIBLE);
			lookaroundBtn.setClickable(true);
		}

		@Override
		public void onError(WeiboDialogError e) {
			Toast.makeText(getApplicationContext(),	"Auth error : " + e.getMessage(), Toast.LENGTH_LONG).show();
			loadingRl.setVisibility(View.INVISIBLE);
			lookaroundBtn.setClickable(true);
		}

		@Override
		public void onCancel() {
			loadingRl.setVisibility(View.INVISIBLE);
			lookaroundBtn.setClickable(true);
		}
		
		

	}
}
